<?php
namespace app\services;

class RetargetService extends BaseService {
    public $matrix = [
        'id'                => 'id',
        'tag'               => 'tag',
        'domain'            => 'url',
        'type'              => 'type',
        'lastModifiedDate'  => 'last_update',
        'code'              => 'code',
        'operate'           => 'edit',
    ];

    public function getAllRetargets() {
        $types = $this->getAll('RetargetType', ['status'=>1]);
        $adId = $this->S('advertiser_id');
        $sites = $this->getAll('RetargetSite', ['advertiser_id' => $adId, 'status'=>1]);
        foreach ($sites as &$site) {
            $typeId = $site['retarget_type_id'];
            $site['type'] = $types[$typeId]['name'];
            $site['code'] = $this->getRetargetCode($site['id']);
        }
        $data = $this->fieldsMap($this->matrix, $sites);
        return $data;
    }

    public function getRetargetCode($tagId) {
        $img = \Yii::$app->params['retarget_check_url'];
        return $img.'?aid='.$tagId;
        //return $this->getSiteBaseUrl().'/index/mark?tag='.$tagId;
    }

    public function addNewRetarget ($data) {
        $data['advertiser_id'] = $this->S('advertiser_id');
        $data['retarget_check_url'] = \Yii::$app->params['retarget_check_url'];
        $attributes = $this->save('RetargetSite', $data);
        if (! empty($attributes)) {
            $data['id'] = $attributes['id'];
            $data['retarget_check_url'] = \Yii::$app->params['retarget_check_url']."?aid=${attributes['id']}";
            return $this->save('RetargetSite', $data);
        }
        return $attributes;
    }

    public function addEditRetarget ($data) {
        $attributes = $this->save('RetargetSite', $data);
        return $attributes;
    }
}//end of creative service declaration

